package cn.virens.mybatis;

import java.io.Serializable;
import java.time.LocalDateTime;

import org.springframework.transaction.annotation.Transactional;

import cn.virens.common.exception.APIException;
import cn.virens.mybatis.mapper.Mapper;

/**
 * 通用service实现类
 * 
 * @author     virens
 * @param  <M> DO层接口类型
 * @param  <T> 实体类型
 */
public abstract class BaseWriteServiceImpl<M extends Mapper<T>, T extends BaseModel> extends BaseReadServiceImpl<M, T> implements BaseWriteService<T> {

	public BaseWriteServiceImpl(Class<T> clazz) {
		super(clazz);
	}

	@Override
	@Transactional(readOnly = false)
	public T insert(T record) throws APIException {
		if (record == null) { return null; }

		// 插入setCreateTime
		record.setCreateTime(LocalDateTime.now());
		record.setUpdateTime(LocalDateTime.now());

		if (mBaseMapper.insertSelective(record) > 0) {
			return record;
		} else {
			return null;
		}
	}

	@Override
	@Transactional(readOnly = false)
	public T update(T record) throws APIException {
		if (record == null) { return null; }

		// 插入setUpdateTime
		record.setUpdateTime(LocalDateTime.now());

		if (mBaseMapper.updateByPrimaryKeySelective(record) > 0) {
			return record;
		} else {
			return null;
		}
	}

	@Override
	@Transactional(readOnly = false)
	public int delete(Serializable id) throws APIException {
		return mBaseMapper.deleteByPrimaryKey(id);
	}
}
